//
//  AdoptDetailViewController.m
//  PigMarket
//
//  Created by mac on 2019/4/8.
//  Copyright © 2019 felix.pigmarket.oc. All rights reserved.
//

#import "AdoptDetailViewController.h"
#import "PigHeaderView.h"
#import "PigPayFooterView.h"
#import "OrderViewController.h"
#import "BuyPigViewController.h"
#import "BuyPigCell.h"
#import "AdoptDetailsCell.h"
#import "AdoptDetailTitleCell.h"
#import "XXTGShareView.h"


@interface AdoptDetailViewController ()

@property (nonatomic, strong) PigHeaderView *headerView;
@property (nonatomic, strong) XXTGShareView *shareView;
@property (nonatomic, strong) PigDetailFooterView *footerView;
@property (nonatomic, strong) AdoptDetailList *dataModel;
@property (nonatomic, strong) NSMutableArray *headImgArr;
@property (nonatomic, strong) NSMutableArray *trusteePriceArr;
@property (nonatomic, strong) NSArray *titles;
@property (nonatomic, strong) NSArray *sections;

@end

@implementation AdoptDetailViewController

#pragma mark - view life cycle

- (void)setupUI{
    
    {
        self.baseNavView.backgroundColor = KClearColor;
        self.baseNavView.line.hidden = YES;
        [self.baseNavView.leftNavBtn setImage:[UIImage imageNamed:@"nav_white"] forState:UIControlStateNormal];
        
        [self.baseNavView.rightNavBtn setImage:[UIImage imageNamed:@"share_icon_white"] forState:UIControlStateNormal];
        self.baseNavView.rightNavBtn.hidden = NO;
        
        [self.view addSubview:self.baseNavView];
        
        @weakify(self);
        self.baseNavView.rightBlock = ^{
            @strongify(self);
            [[UIApplication sharedApplication].keyWindow addSubview:self.shareView];
            [self.shareView showShare];
        };
    }
    
    
    [self initAction];
}


- (void)setupLayout{
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(- TJ_StatusBarHeight, 0, -TJ_SafeAreaBottomHeight-5 , 0));
    }];
}

- (void) initAction {
    //保存数值，区分小猪托管费用  仔猪是否默认选择
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    [user setValue:@"NO" forKey:@"pigTrusteeIsSelect"];
}


- (void)initData {
    [self dataRequest];
}

#pragma mark - private method
- (void)dataRequest {
    
    NSNumber *tribeId = [UserInfoDataProvider sharedInstance].userInfo.tribeId;
    NSNumber *pigId = [UserInfoDataProvider sharedInstance].userInfo.pigId;
    
    @weakify(self);
    [[[PigMarketApi sharedInstance] adoptDetailWithPigId:pigId tribeId:tribeId] subscribeNext:^(AdoptDetailList * _Nullable adoptDetailList) {
        @strongify(self);
        self.dataModel = adoptDetailList;
        [self.headImgArr addObjectsFromArray:adoptDetailList.maters];
        [self.trusteePriceArr addObjectsFromArray:adoptDetailList.stagePrices];
        
        self.headerView.headerDataArr = self.headImgArr;
        self.headerView.dataModel = self.dataModel;
        
        [self.tableView reloadData];
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self handlingError:error];
    }];
}


- (BOOL)isAgreeAdoptAgreement {
    
    if (!self.footerView.confirmAgreementBtn.selected) {
        [self toastWithContent:@"请阅读并同意领养协议"];
        return NO;
    }
    return YES;
}


#pragma mark - target action
//返回
- (void)backTapped {
    [self.navigationController popViewControllerAnimated:YES];
}

//免费领养
- (void)freeAdoptTapped {
    if (![self isAgreeAdoptAgreement]) {
        return;
    }
    NSNumber *tribeId = [UserInfoDataProvider sharedInstance].userInfo.tribeId;
    NSNumber *pigId = [UserInfoDataProvider sharedInstance].userInfo.pigId;
    NSNumber *memberId = [UserInfoDataProvider sharedInstance].userInfo.memberId;

    PayParam *param = [[PayParam alloc] init];
    param.adoptType = @(UnAdoptTypeFree);
    param.tribeId = tribeId;
    param.pigId = pigId;
    param.memberId = memberId;
    @weakify(self);
    [[[PigMarketApi sharedInstance] payWithParam:param] subscribeNext:^(Pay * _Nullable model) {
        @strongify(self);
        
        NSString *message = [NSString stringWithFormat:@"编号%@的小猪试样申请已提交，请您耐心等待。申请通过后，您可以通过监控看到它的生活状态。试养期最长3天，中途有人领养或预定，试养自动结束。",model.pigNum];
        [self showAlertByTitle:@"等待审核" Text:message isPop:YES];

    } error:^(NSError * _Nullable error) {
        @strongify(self);
        NSString *contentText = error.userInfo[NSLocalizedDescriptionKey];
        [self showAlertByTitle:@"请勿再次申请" Text:contentText isPop:NO];

    }];
}

- (void)showAlertByTitle:(NSString *)title Text:(NSString *)text isPop:(BOOL)pop{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:text preferredStyle:UIAlertControllerStyleAlert];
    
    @weakify(self);
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        @strongify(self);
        if (pop) {
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
    }];
    [okAction setValue:mMainColor forKey:@"titleTextColor"];
    [alert addAction:okAction];
    [self presentViewController:alert animated:YES completion:nil];
}


//99预定
- (void)orderAdoptTapped {
    
    if (![self isAgreeAdoptAgreement]) {
        return;
    }
    
    OrderViewController *orderVC = [[OrderViewController alloc] init];
    orderVC.detailModel = self.dataModel;
    [self.navigationController pushViewController:orderVC animated:YES];
}


//立即领养
- (void)adoptTapped {
    
    if (![self isAgreeAdoptAgreement]) {
        return;
    }
    BuyPigViewController *buyVC = [[BuyPigViewController alloc] init];
    buyVC.detailModel = self.dataModel;
    [self.navigationController pushViewController:buyVC animated:YES];
    
}


#pragma mark - delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section == 0) return  3 + (self.trusteePriceArr.count -1);
    return 5;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) return 42;
    if (indexPath.section == 0) {
        if (indexPath.row == self.trusteePriceArr.count + 1 || indexPath.row == 1) {
            return 15;
        }
    }else if(indexPath.section == 1){
        if (indexPath.row == 4 || indexPath.row == 1) {
            return 15;
        }
    }
    return 44;
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return section == 0 ?10 :0.001;
}


- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    return [UIView new];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.row == 0){
        AdoptDetailTitleCell *titleCell = [tableView dequeueReusableCellWithIdentifier:@"AdoptDetailTitleCell"];
        titleCell.titleLab.text = self.sections[indexPath.section];
        titleCell.type = @(indexPath.section);
        titleCell.detailLab.text = [NSString stringWithFormat:@"%@个", @(self.trusteePriceArr.count -2)];
        return titleCell;
    }

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    if (indexPath.section == 0) {
        
        if (indexPath.row == self.trusteePriceArr.count +1 || indexPath.row == 1) {
            return cell;
        }
        
    }else{
        if (indexPath.row == 4|| indexPath.row == 1) {
            return cell;
        }
    }
    
    AdoptDetailsCell *bodyCell = [tableView dequeueReusableCellWithIdentifier:@"AdoptDetailsCell"];
    bodyCell.bgColor = indexPath.row %2 == 0 ?UIColorFromRGB(0xDCF2CB) :RGB(211, 235, 186);
    
    if (indexPath.row < self.trusteePriceArr.count+3) {
        
        AdoptDetail *item = nil;
        if (indexPath.section == 0) {
            item = self.trusteePriceArr[indexPath.row - 2];
        }else{
            item = [self.trusteePriceArr lastObject];
        }
        
        if (indexPath.row >=3) {
            bodyCell.item = item;

        }else{
            bodyCell.nameLab.text = self.titles[0];
            bodyCell.priceLab.text = self.titles[1];
            bodyCell.dayLab.text = self.titles[2];
        }
    }
    
    return bodyCell;
}


#pragma mark - getter and setter

- (void)registerTableViewCell{
    
    self.tableView.mj_footer.hidden = YES;
    self.tableView.mj_header.hidden = YES;
    self.tableView.tableHeaderView = self.headerView;
    self.tableView.tableFooterView = self.footerView;
    
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
    [self.tableView registerClass:[AdoptDetailsCell class] forCellReuseIdentifier:@"AdoptDetailsCell"];
    [self.tableView registerClass:[AdoptDetailTitleCell class] forCellReuseIdentifier:@"AdoptDetailTitleCell"];

}


-(PigHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[PigHeaderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 410 + ScaleHeight(240))];
        _headerView.backgroundColor = [UIColor globalBackgroundColor];
        
        @weakify(self);
        _headerView.dealRecipeBlock = ^{
            @strongify(self);
            [self showHudWithMsg:@"食谱"];
        };
        
        _headerView.dealFeedingBlock = ^{
            @strongify(self);
            [self showHudWithMsg:@"喂养"];
        };

    }
    return _headerView;
}


- (PigDetailFooterView *)footerView{
    
    if (!_footerView) {
        _footerView =  [[PigDetailFooterView alloc] init];
        _footerView.frame = CGRectMake(0, 0, KScreenWidth, 110+TJ_SafeAreaBottomHeight);
        [_footerView.freeAdoptBtn addTarget:self action:@selector(freeAdoptTapped) forControlEvents:UIControlEventTouchUpInside];
        [_footerView.orderBtn addTarget:self action:@selector(orderAdoptTapped) forControlEvents:UIControlEventTouchUpInside];
        [_footerView.adoptBtn addTarget:self action:@selector(adoptTapped) forControlEvents:UIControlEventTouchUpInside];
    }
    return _footerView;
}


- (XXTGShareView *)shareView
{
    if (!_shareView) {
        _shareView = [[XXTGShareView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight)];
        
        @weakify(self);
        _shareView.dealShareBlock = ^(NSInteger params) {
            @strongify(self);
            
            switch (params) {
                case 0:
                {
                    [self showHudWithMsg:@"微信"];
                }
                    break;
                    
                case 1:
                {
                    [self showHudWithMsg:@"朋友圈"];
                    
                }
                    break;
                    
                case 2:
                {
                    [self showHudWithMsg:@"微博"];
                    
                }
                    break;
                    
                case 3:
                {
                    [self showHudWithMsg:@"QQ"];
                }
                    break;
                    
                case 4:
                {
                    [self showHudWithMsg:@"站内豚友"];
                    
                }
                    break;
                    
                case 5:
                {
                    [self showHudWithMsg:@"QQ空间"];
                    
                }
                    break;
                    
                default:
                {
                    [self showHudWithMsg:@"复制链接"];
                    
                }
                    break;
            }
        };
        
    }
    return _shareView;
}


- (NSMutableArray *)headImgArr {
    if (!_headImgArr) {
        _headImgArr = [[NSMutableArray alloc] init];
    }
    return _headImgArr;
}


- (NSMutableArray *)trusteePriceArr {
    if (!_trusteePriceArr) {
        _trusteePriceArr = [[NSMutableArray alloc] init];
    }
    return _trusteePriceArr;
}


- (AdoptDetailList *)dataModel {
    if (!_dataModel) {
        _dataModel = [[AdoptDetailList alloc] init];
    }
    return _dataModel;
}

- (NSArray *)titles{
    
    if (!_titles) {
        _titles = @[@"项目名称", @"当期费用", @"周期天数"];
    }
    return _titles;
}

- (NSArray *)sections{
    
    if (!_sections) {
        _sections = @[@"托管阶段", @"托管全包"];
    }
    return _sections;
}


@end

